var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var colors = require('colors');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var log4js = require('log4js');
var fs = require('fs');
var routes = require('./routes/index');

const TARGET = process.env.npm_lifecycle_event;
var app = express();

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

var log4js = require('log4js');
log4js.configure({
    appenders: [{
          "type": "file",
          "filename": "logs/log_file.log",
          "maxLogSize": 20480,
          "backups": 3,
          "category": "relative-logger"
        }
    ]
})
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//routes
//接口routes
app.use('/api', routes);

//single page logic
if (TARGET == 'dev' || !TARGET) {
    app.use(express.static(path.join(__dirname, '/dist')));
    app.get('*', function response(req, res) {
        res.write(fs.readFileSync(path.join(__dirname, 'dist/index.html')));
        res.end();
    });
} else if (TARGET === 'start') {
    app.use(express.static(path.join(__dirname, '/dist')));
    app.get('*', function response(req, res) {
        res.sendFile(path.join(__dirname, 'dist/index.html'));
    });
}

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (TARGET == 'dev' || !TARGET) {
    app.use(function(err, req, res, next) {
        console.log(err)
        res.status(err.status || 500);
        res.write(err.toString());
        res.end();
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    console.log(err)
    res.status(err.status || 500);
    res.sendFile(path.join(__dirname, 'dist/index.html'));
});


module.exports = app;